package com.zhutengwei.android.zuji.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.zhutengwei.android.zuji.R;
import com.zhutengwei.android.zuji.db.TableDao;
import com.zhutengwei.android.zuji.model.UserModel;
import com.zhutengwei.android.zuji.tool.Constant;

import static android.content.SharedPreferences.*;

/**
 * Created by Administrator on 2016/11/27.
 */
public class LoginActivity extends BaseActivity {
    private EditText email;
    private EditText userpass;
    private Button login;
    private TextView login_link;
    TableDao dao = new TableDao(this);
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        email = (EditText) findViewById(R.id.login_input_email);
        userpass = (EditText) findViewById(R.id.login_input_password);
        login = (Button) findViewById(R.id.btn_login);
        login_link = (TextView) findViewById(R.id.link_signup);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
        login_link.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this,
                        RegisterActivity.class));
            }
        });
    }

    private void login() {
        UserModel user;
        user = dao.getUserByEmail(email.getText().toString());
        if(user != null){
            if(user.getUserpass().equals(userpass.getText().toString())){
                //通过sharedpreferences保存email
                SharedPreferences sp =
                        getSharedPreferences(Constant.TAG, Context.MODE_PRIVATE);
                Editor editor = sp.edit();
                editor.putString(Constant.EMAIL, user.getEmail());
                editor.commit();

                Intent i = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(i);
                Toast.makeText(this, "登录成功！",Toast.LENGTH_LONG).show();
                finish();
            } else {
                Toast.makeText(this, "密码输入错误！",Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(this, "该用户没有注册！",Toast.LENGTH_LONG).show();
        }
    }
}
